/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.controller.admin;

import java.util.HashSet;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.Message;
import com.finalist.Pageable;
import com.finalist.entity.Admin;
import com.finalist.entity.BaseEntity.Save;
import com.finalist.entity.Role;
import com.finalist.service.AdminService;
import com.finalist.service.AreaStandardCodeService;
import com.finalist.service.BossAreaService;
import com.finalist.service.PaymentService;
import com.finalist.service.RoleService;

/**
 * Controller - 管理员
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Controller("adminAdminController")
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

	@Resource(name = "adminServiceImpl")
	private AdminService adminService;
	@Resource(name = "roleServiceImpl")
	private RoleService roleService;
	
	@Resource(name = "areaStandardCodeServiceImpl")
	private AreaStandardCodeService areaStandardCodeService;
	
	
	@Resource(name = "bossAreaServiceImpl")
	private BossAreaService bossAreaService;
	
	@Resource(name = "paymentServiceImpl")
	private PaymentService paymentService;
	private Logger log = Logger.getLogger(AdminController.class);
	/**
	 * 检查用户名是否存在
	 */
	@RequestMapping(value = "/check_username", method = RequestMethod.GET)
	public @ResponseBody
	boolean checkUsername(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		if (adminService.usernameExists(username)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {
		model.addAttribute("roles", roleService.findAll());
		return "/admin/admin/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Admin admin, Long[] roleIds, RedirectAttributes redirectAttributes) {
		admin.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		if (!isValid(admin, Save.class)) {
			return ERROR_VIEW;
		}
		if (adminService.usernameExists(admin.getUsername())) {
			return ERROR_VIEW;
		}
		admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		admin.setIsLocked(false);
		admin.setLoginFailureCount(0);
		admin.setLockedDate(null);
		admin.setLoginDate(null);
		admin.setLoginIp(null);
		admin.setOrders(null);
		admin.setIsCheck(true);
		try {
			adminService.save(admin);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {
		model.addAttribute("roles", roleService.findAll());
		model.addAttribute("admin", adminService.find(id));
		return "/admin/admin/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Admin admin, Long[] roleIds, RedirectAttributes redirectAttributes) {
		admin.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		if (!isValid(admin)) {
			return ERROR_VIEW;
		}
		Admin pAdmin = adminService.find(admin.getId());
		if (pAdmin == null) {
			return ERROR_VIEW;
		}
//		if (StringUtils.isNotEmpty(admin.getPassword())) {
//			admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
//		} else {
//			admin.setPassword(pAdmin.getPassword());
//		}
		if (pAdmin.getIsLocked() && !admin.getIsLocked()) {
			admin.setLoginFailureCount(0);
			admin.setLockedDate(null);
		} else {
			admin.setIsLocked(pAdmin.getIsLocked());
			admin.setLoginFailureCount(pAdmin.getLoginFailureCount());
			admin.setLockedDate(pAdmin.getLockedDate());
		}
		adminService.update(admin, "username","loginDate", "loginIp", "orders","step","isCheck","password","type","ticket","hasEmailAction","registerTime","partner","selleEmail","safeKey","mchId","paternerKey");
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 
	 * @param flag 0:所有 1 通过  2 审核未通过 3 未审核
	 * @param pageable
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Integer flag ,Pageable pageable, ModelMap model) {
		model.addAttribute("flag", flag);
		model.addAttribute("page", adminService.findPage(flag,pageable));
		return "/admin/admin/list";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Message delete(Long[] ids) {
		if (ids.length >= adminService.count()) {
			return Message.error("admin.common.deleteAllNotAllowed");
		}
		adminService.delete(ids);
		return SUCCESS_MESSAGE;
	}
	
	
	/**
	 * 前往电信补充充值页面
	 */
	@RequestMapping(value = "/toBuChong", method = RequestMethod.GET)
	public String toBuChong() {
		
		return "/admin/buchong/dianxinbuchong";
	}
	
	
	
	/**
	 * 联通,电信补充话费
	 * 联通不包括调用金力接口
	 */
	@RequestMapping(value = "/buChong", method = RequestMethod.POST)
	public String buchong(String type,String sn,String amount,String phone,ModelMap model,RedirectAttributes redirectAttributes) {
		
	
		return "redirect:toBuChong.jhtml";
		
	}
	/**
	 * 审核
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	public String check(Long id, ModelMap model) {
		model.addAttribute("roles", roleService.findAll());
		model.addAttribute("admin", adminService.find(id));
		return "/admin/admin/check";
	}
	/**
	 * 审核通过更新
	 * @param admin
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/checkUpdate", method = RequestMethod.POST)
	public String checkUpdate(Admin admin,Long[] roleIds, RedirectAttributes redirectAttributes) {
		Admin persit = adminService.find(admin.getId());
		persit.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		persit.setIsCheck(true);
		persit.setReason(admin.getReason());
		adminService.update(persit);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}
	
	/**
	 * 审核未通过更新
	 * @param admin
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/checkNoPassUpdate", method = RequestMethod.POST)
	public String checkNoPassUpdate(Admin admin,Long[] roleIds, RedirectAttributes redirectAttributes) {
		Admin persit = adminService.find(admin.getId());
		persit.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		persit.setIsCheck(false);
		persit.setReason(admin.getReason());
		adminService.update(persit);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

}